<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/3/23
 * Time: 10:07
 */

namespace app\api\controller;
use app\common\controller\Api;
use think\Request;
use addons\third\library\Wechat as WechatModel;
use fast\Random;
use think\Db;
use app\common\library\Token;

//use think\Loader;
class Wechat extends Api
{
    protected $noNeedLogin = ['getInfo'];
    protected $noNeedRight = '*';
    protected $keeptime = 2592000;
    protected $_token = '';
    public static $model = null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        if(!self::$model)
        {
            self::$model = new WechatModel(['callback'=>'']);
        }
    }

    public function getUserInfo()
    {
        if(!$code = input('post.code'))
            $this->error('缺少参数');
        $res = self::$model->getUserInfo(['code'=>$code]);
        if(!$res)
            $this->error('授权失败');
        $this->success('',$res);

    }

    /**
     * 设置会话有效时间
     * @param int $keeptime 默认为永久
     */
    public function keeptime($keeptime = 0)
    {
        $this->keeptime = $keeptime;
    }

    public function getInfo()
    {

        $code = input('code');
        //$oauth= Config::get('wechat.oauth');
        $oauth = get_addon_config('third')['wechat'];

        $appid = $oauth['app_id'];
        $appserect = $oauth['app_secret'];

        $url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appserect&js_code=".$code;

        $info  = $this->https_request($url);
        $json  = json_decode($info,true);

        if(!empty($json['openid'])){

            /*$encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
                QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
                9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
                3hVbJSRgv+4lGOETKUQz6OYStslQ142d
                NCuabNPGBzlooOmB231qMM85d2/fV6Ch
                evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
                /1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
                u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
                /Hz7saL8xz+W//FRAUid1OksQaQx4CMs
                8LOddcQhULW4ucetDf96JcR3g0gfRK4P
                C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
                6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
                /8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
                lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
                oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
                20f0a04COwfneQAGGwd5oa+T8yO5hzuy
                Db/XcxxmK01EpqOyuxINew==";

            $iv = 'r7BXXKkLb8qrSNn05n0qiA==';
            $pc = new \vx\WxBizDataCrypt($appid,$json['session_key']);

            $errCode = $pc->decryptData($encryptedData, $iv, $data );
            $data = json_decode($data);
            if ($errCode == 0) {
                echo '解密结果';
                dump($data);
                die;//打印解密所得的用户信息
            } else {
                echo $errCode;//打印失败信息
            }*/

            $salt = Random::alnum();

            $info = Db::name('user')->field('id,username,nickname,mobile,avatar,bio,authorize')->where('openid',$json['openid'])->find();
            $rand = rand(0, 9999);
            if(empty($info)){
                $params['password'] = $this->getEncryptPassword('123456', $salt);
                $data['nickname']  = '游客'.$rand;
                $data['username'] = '游客'.$rand;
                $data['openid'] = $json['openid'];
                $data['createtime'] = time();
                $data['level'] = 1;
                $data['status'] = 'normal';
                $data['score'] = 0;
                $data['salt'] = $salt;
                $data['avatar'] = '';
                $data['bio'] = '';

                $res = Db::name('user')->insertGetId($data);
                $this->_token = Random::uuid();
                Token::set($this->_token, $res, $this->keeptime);
                if($res){
                    unset($data['openid']);
                    unset($data['salt']);
                    $msg = Token::get($this->_token);
                    $data['token'] = $msg['token'];
                    $data['session_key'] = $json['session_key'];
                    $data['authorize'] = 0;
                    $this->success('登入成功',$data);
                }
                else
                {
                    $this->error('登入失败');
                }
            }else{

                $this->_token = Random::uuid();
                Token::set($this->_token, $info['id'], $this->keeptime);

                $res = Token::get($this->_token);
                $info['token'] = $res['token'];
                $info['session_key'] = $json['session_key'];
                $this->success('',$info);
            }

        }
        else
        {
            $this->error($json['errmsg']);
        }

    }

    /**
     * 绑定手机号
     */
    public function bindMobile()
    {
        if (!Request::instance()->isPost())
            $this->error('请求方式不正确');
        $oauth = get_addon_config('third')['wechat'];
        $appid = $oauth['app_id'];
        $session_key = input('post.session_key');
        $iv = input('post.iv');
        $encryptedData = input('post.encryptedData');
        //$mobile = input('post.mobile');

        $pc = new \vx\WxBizDataCrypt($appid,$session_key);

        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            $data = json_decode($data,true);
           $res = Db::name('user')->where('id',$this->auth->id)->update(['mobile'=>$data['phoneNumber']]);
           if($res)
           {
               $this->success('绑定成功');
           }
           $this->error('绑定失败');
        } else {
            $this->error('绑定失败');
        }
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public static function https_request($curl, $data=null, $https=true, $method='post'){
        $ch = curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL, $curl);//设置访问的URL
        curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
        if($https){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
        }
        if($method == 'post'){
            curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
        }
        $str = curl_exec($ch);//执行访问，返回结果
        curl_close($ch);//关闭curl，释放资源
        return $str;
    }

    public function saveInformation()
    {
        $params = input('post.');
        $user_id = $this->auth->id;
        $res = Db::name('user')->where('id',$user_id)->update(['nickname'=>$params['nickname'],'username'=>$params['nickname'],'avatar'=>$params['avatar'],'authorize'=>1]);

        if($res!==false)
            $this->success('','更新成功');
        $this->error('更新失败');
    }


}